﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace WinFormsAppCV
{
    internal partial class InputSimulator
    {
        internal Point Point { get; set; }
        private readonly Action<string> Echo;
        internal InputSimulator(Action<string> action)
        {
            this.Echo = action;
        }

        [LibraryImport("user32.dll")]
        private static partial void mouse_event(uint dwFlags, uint dx, uint dy, uint dwData, int dwExtraInfo);

        private const uint MOUSEEVENTF_LEFTDOWN = 0x02;
        private const uint MOUSEEVENTF_LEFTUP = 0x04;

        [LibraryImport("user32.dll")]
        private static partial void keybd_event(byte bVk, byte bScan, uint dwFlags, int dwExtraInfo);

        const int KEYEVENTF_KEYDOWN = 0x0000;
        const int KEYEVENTF_KEYUP = 0x0002;

        [LibraryImport("user32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        private static partial bool SetCursorPos(int X, int Y);

        /// <summary>
        /// 按键
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        internal InputSimulator Key(Keys key)
        {
            keybd_event((byte)key, 0, KEYEVENTF_KEYDOWN, 0); // 按下
            keybd_event((byte)key, 0, KEYEVENTF_KEYUP, 0);   // 释放
            Echo($"成功按下按键: ({key}");

            return this;
        }

        /// <summary>
        /// 设置坐标
        /// </summary>
        /// <returns></returns>
        internal InputSimulator CursorPosition()
        {
            if (Point == default)
            {
                return this;
            }

            SetCursorPos(Point.X, Point.Y);
            Echo($"成功设置坐标: ({Point.X}, {Point.Y})");

            return this;
        }

        /// <summary>
        /// 鼠标左击
        /// </summary>
        /// <returns></returns>
        internal InputSimulator MouseLeftClick()
        {
            if (Point == default)
            {
                return this;
            }

            CursorPosition();
            mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, 0, 0, 0, 0);
            Echo($"成功点击坐标: ({Point.X}, {Point.Y})");

            return this;
        }
    }
}
